package com.hckjsec.cloud.controller;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hckjsec.cloud.domain.JiShiBanView;
import com.hckjsec.cloud.domain.jishiban.*;
import com.hckjsec.cloud.domain.wechatDataView.CurrencyView;
import com.hckjsec.cloud.domain.zipcode.DivisionCityView;
import com.hckjsec.cloud.domain.zipcode.DivisionCountyView;
import com.hckjsec.cloud.domain.zipcode.DivisionProvinceView;
import com.hckjsec.cloud.service.WxSendTplMessageService;
import com.hckjsec.common.constant.Constants;
import com.hckjsec.common.core.redis.RedisCache;
import com.hckjsec.common.utils.ComUtil;
import com.hckjsec.common.utils.DistanceCalculation;
import com.hckjsec.common.utils.SecurityUtils;
import com.hckjsec.common.utils.StringUtils;
import com.hckjsec.common.utils.http.HttpUtils;
import com.hckjsec.system.domain.SysPostalcode;
import com.hckjsec.system.service.ISysPostalcodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.hckjsec.common.annotation.Log;
import com.hckjsec.common.core.controller.BaseController;
import com.hckjsec.common.core.domain.AjaxResult;
import com.hckjsec.common.enums.BusinessType;
import com.hckjsec.cloud.domain.AppletsPublicJishiban;
import com.hckjsec.cloud.service.IAppletsPublicJishibanService;
import com.hckjsec.common.utils.poi.ExcelUtil;
import com.hckjsec.common.core.page.TableDataInfo;

/**
 * 冀时办Controller
 * 
 * @author cyt
 * @date 2021-09-23
 */
@RestController
@RequestMapping("/system/jishiban")
public class AppletsPublicJishibanController extends BaseController
{
    @Autowired
    private IAppletsPublicJishibanService appletsPublicJishibanService;

    @Autowired
    private ISysPostalcodeService sysPostalcodeService;

    @Autowired
    private WxSendTplMessageService wxSendTplMessageService;

    @Autowired
    private RedisCache redisCache;
    /**
     * 查询冀时办列表
     */
    @GetMapping("/list")
    public TableDataInfo list(AppletsPublicJishiban appletsPublicJishiban)
    {
        startPage();
        List<AppletsPublicJishiban> list = appletsPublicJishibanService.selectAppletsPublicJishibanList(appletsPublicJishiban);
        return getDataTable(list);
    }

    /**
     * 导出冀时办列表
     */
    @Log(title = "冀时办", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(AppletsPublicJishiban appletsPublicJishiban)
    {
        List<AppletsPublicJishiban> list = appletsPublicJishibanService.selectAppletsPublicJishibanList(appletsPublicJishiban);
        ExcelUtil<AppletsPublicJishiban> util = new ExcelUtil<AppletsPublicJishiban>(AppletsPublicJishiban.class);
        return util.exportExcel(list, "jishiban");
    }

    /**
     * 获取冀时办详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        AppletsPublicJishiban appletsPublicJishiban = appletsPublicJishibanService.selectAppletsPublicJishibanById(id);
        String code = appletsPublicJishiban.getProvinceCode()+","+appletsPublicJishiban.getCityCode()+","+appletsPublicJishiban.getCode();
        appletsPublicJishiban.setCode(code);
        return AjaxResult.success(appletsPublicJishiban);
    }

    /**
     * 新增冀时办
     */
    @Log(title = "冀时办", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AppletsPublicJishiban appletsPublicJishiban)
    {
        String[] codeArr = appletsPublicJishiban.getCode().split(",");
        appletsPublicJishiban.setProvinceCode(codeArr[0]);
        appletsPublicJishiban.setCityCode(codeArr[1]);
        appletsPublicJishiban.setCode(codeArr[2]);
        appletsPublicJishiban.setOperator(SecurityUtils.getUserId());
        return toAjax(appletsPublicJishibanService.insertAppletsPublicJishiban(appletsPublicJishiban));
    }

    /**
     * 修改冀时办
     */
    @Log(title = "冀时办", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AppletsPublicJishiban appletsPublicJishiban)
    {
        String[] codeArr = appletsPublicJishiban.getCode().split(",");
        appletsPublicJishiban.setProvinceCode(codeArr[0]);
        appletsPublicJishiban.setCityCode(codeArr[1]);
        appletsPublicJishiban.setCode(codeArr[2]);
        appletsPublicJishiban.setOperator(SecurityUtils.getUserId());
        return toAjax(appletsPublicJishibanService.updateAppletsPublicJishiban(appletsPublicJishiban));
    }

    /**
     * 删除冀时办
     */
    @Log(title = "冀时办", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(appletsPublicJishibanService.deleteAppletsPublicJishibanByIds(ids));
    }


    /**
     * 获取站点APPid
     */
    @GetMapping("/getCodeList")
    public AjaxResult getCodeList()
    {
        //第一步查询所有省份
        List<DivisionProvinceView> divisionProvinceViewList = new ArrayList<DivisionProvinceView>();
        SysPostalcode postalcode = new SysPostalcode();
        postalcode.setCodeType("1");
        postalcode.setCode("13");
        List<SysPostalcode>  plist = sysPostalcodeService.selectSysPostalcodeList(postalcode);
        plist.forEach(pkv->{
            DivisionProvinceView divisionProvinceView = new DivisionProvinceView();
            divisionProvinceView.setValue(pkv.getCode());
            divisionProvinceView.setLabel(pkv.getCodeName());
            List<DivisionCityView> divisionCityViewList = new ArrayList<>();
            //查询省份下所有市
            SysPostalcode costalcode = new SysPostalcode();
            costalcode.setProvinceCode(pkv.getCode());
            costalcode.setCodeType("2");
            List<SysPostalcode>  clist = sysPostalcodeService.selectSysPostalcodeList(costalcode);
            clist.forEach(ckv->{
                DivisionCityView  divisionCityView = new DivisionCityView();
                divisionCityView.setValue(ckv.getCode());
                divisionCityView.setLabel(ckv.getCodeName());
                //查询市下面所有县
                List<DivisionCountyView> divisionCountyViewList = new ArrayList<>();
                SysPostalcode countycode = new SysPostalcode();
                countycode.setCityCode(ckv.getCode());
                countycode.setCodeType("3");
                List<SysPostalcode>  countylist = sysPostalcodeService.selectSysPostalcodeList(countycode);
                countylist.forEach(countykv->{
                    DivisionCountyView divisionCountyView = new DivisionCountyView();
                    divisionCountyView.setValue(countykv.getCode());
                    divisionCountyView.setLabel(countykv.getCodeName());
                    divisionCountyViewList.add(divisionCountyView);
                });
                divisionCityView.setChildren(divisionCountyViewList);
                divisionCityViewList.add(divisionCityView);
            });
            divisionProvinceView.setChildren(divisionCityViewList);
            divisionProvinceViewList.add(divisionProvinceView);
        });
        return AjaxResult.success(divisionProvinceViewList);
    }



    //冀时办初始化
    @PostMapping("/jiShiBanInfo")
    public AjaxResult jiShiBanInfo(@RequestBody JiShiBanView jiShiBanView)
    {
        JshibanPublicView jshibanPublicView = new JshibanPublicView();
        String  name = "衡水市";
        String accessLink = StringUtils.isHcNull(jiShiBanView.getAccessLink(),"");
        String addrCode = StringUtils.isHcNull(jiShiBanView.getAddrCode(),"");
        String times = StringUtils.isHcNull(jiShiBanView.getTimes(),"");
        if ("".equals(addrCode)){
            addrCode = "1311";
        }
//        String  oldAddrCode = addrCode;
//        if ("".equals(addrCode)){
//            addrCode = "13";
//        }else{
//            boolean flag = StringUtils.startsWith(addrCode, "13");//判断是否是河北省的地区编码
//            if (!flag){
//                addrCode = "13";
//            }
//        }
//        if (addrCode.length()>4){
//            addrCode = addrCode.substring(0,4);
//        }
        SysPostalcode oldPostalcode  = sysPostalcodeService.selectSysPostalcodeById(addrCode);
        if (StringUtils.isNotNull(oldPostalcode)){
            name = oldPostalcode.getCodeName();
        }
        jshibanPublicView.setName(name);
        List<AppletsPublicJishiban> appletsPublicJishibanList = new ArrayList<>();
        if ("1311".equals(addrCode)){
            appletsPublicJishibanList = appletsPublicJishibanService.selectAppletsPublicJishibanList(new AppletsPublicJishiban("13","true"));
        }else{
            AppletsPublicJishiban appletsPublicJishiban = new AppletsPublicJishiban();
            appletsPublicJishiban.setProvinceCode("13");
            appletsPublicJishiban.setCode(addrCode);
            appletsPublicJishiban.setState("true");
            appletsPublicJishibanList = appletsPublicJishibanService.selectAppletsPublicJishibanList(appletsPublicJishiban);
        }
//        if (StringUtils.isEmpty(appletsPublicJishibanList) && !"2".equals(times)){
//            appletsPublicJishibanList = appletsPublicJishibanService.selectAppletsPublicJishibanList(new AppletsPublicJishiban("13","true"));
//        }
        //通过冀时办拉取人员数据并生成小程序码
//        String  applicationId = "";
//        if (!"".equals(accessLink)){
//              applicationId = getCodeUrl(accessLink);
//        }
        //遍历查看  二维码是否有自动生成的
        List<JiShiBanData> jiShiBanDataList = new ArrayList<>();
//        String finalApplicationId = StringUtils.isHcNull(applicationId,"");
//        AtomicInteger pxAtomic= new AtomicInteger(1);
        appletsPublicJishibanList.forEach(kv->{
//            int px = pxAtomic.get();
            JiShiBanData jiShiBanData = new JiShiBanData();
            jiShiBanData.setName(kv.getMechanismName());
            jiShiBanData.setPhone(kv.getMechanismPhone());
            jiShiBanData.setAddress(kv.getMechanismAddress());
            jiShiBanData.setDefaultPath(kv.getAppletImg());
            jiShiBanData.setCodePath(null);
            jiShiBanData.setSort(kv.getSort());
//            if (oldAddrCode.equals(kv.getCode())){
//                jiShiBanData.setSort(0L);
//            }else{
//                jiShiBanData.setSort(Long.valueOf(px));
//                px++;
//                pxAtomic.set(px);
//            }
//            if (!"".equals(finalApplicationId)) {
//                String codePath =  wxSendTplMessageService.getCodePath(kv,finalApplicationId);
//                jiShiBanData.setCodePath(codePath);
//            }
            jiShiBanDataList.add(jiShiBanData);
        });
//        if (jiShiBanDataList.size()>0){
//            jiShiBanDataList.sort(Comparator.comparing(JiShiBanData::getSort));
//        }
        jshibanPublicView.setDataList(jiShiBanDataList);
        List<CurrencyView> cityList = new ArrayList<>();
        SysPostalcode postalcode = new SysPostalcode();
        postalcode.setCodeType("3");
        postalcode.setProvinceCode("13");
        postalcode.setCityCode("1311");
        List<SysPostalcode>  plist = sysPostalcodeService.selectSysPostalcodeList(postalcode);
        plist.forEach(kv->{
            CurrencyView currencyView = new CurrencyView();
            currencyView.setKey(kv.getCode());
            currencyView.setValue(kv.getCodeName());
            cityList.add(currencyView);
        });
        cityList.sort(Comparator.comparing(CurrencyView::getKey));
        jshibanPublicView.setCityList(cityList);
        return AjaxResult.success(jshibanPublicView);
    }

    public String getCodeUrl(String accessLink){
        String rspStr = HttpUtils.sendGet(ComUtil.JISHIBAN_URL, "C-App-Id="+ComUtil.JISHIBAN_APPID+"&appPwd="+ComUtil.JISHIBAN_PWD+"&accessLink="+accessLink, Constants.UTF8);
        JSONObject reuslt = JSON.parseObject(rspStr);
        String random="";
        if (reuslt.containsKey("C-API-Status")){
            String code=String.valueOf(reuslt.get("C-API-Status"));
            if ("00".equals(code)){
                if (reuslt.containsKey("C-Response-Body")){
                    String body = StringUtils.isHcNull(String.valueOf(reuslt.get("C-Response-Body")),"");
                    if (!"".equals(body) && !"null".equals(body)){
                        random=ComUtil.getRandom(9);
                        InterfaceBackUser interfaceBackUser=JSON.parseObject(body,InterfaceBackUser.class);
                        interfaceBackUser.setApplicationId(random);
                        redisCache.setCacheObject(Constants.JISHIBAN_USER + random,interfaceBackUser, 4, TimeUnit.HOURS);
                    }
                }
            }
        }
        return random;
    }

    //冀时办初始化
    @PostMapping("/getJiShiBanInfo")
    public AjaxResult getJiShiBanInfo(@RequestBody AppletsJiShiBanView appletsJiShiBanView)
    {
        AppletsJshibanPublicView appletsJshibanPublicView = new AppletsJshibanPublicView();
        String zipCode = StringUtils.isHcNull(appletsJiShiBanView.getZipCode(),"");
        String longitude = StringUtils.isHcNull(appletsJiShiBanView.getLongitude(),"");
        String latitude = StringUtils.isHcNull(appletsJiShiBanView.getLatitude(),"");
        List<AppletsPublicJishiban> appletsPublicJishibanList = new ArrayList<>();
        if (!"".equals(zipCode)){//如果邮编不为空
            AppletsPublicJishiban appletsPublicJishiban = new AppletsPublicJishiban();
            appletsPublicJishiban.setProvinceCode("13");
            appletsPublicJishiban.setCode(zipCode);
            appletsPublicJishiban.setState("true");
            appletsPublicJishibanList = appletsPublicJishibanService.selectAppletsPublicJishibanList(appletsPublicJishiban);
        } else {
            appletsPublicJishibanList = appletsPublicJishibanService.selectAppletsPublicJishibanList(new AppletsPublicJishiban("13","true"));
        }
        List<AppletsJiShiBanData> jiShiBanDataList = new ArrayList<>();
        if (!"".equals(longitude) && !"".equals(latitude)) {//如果经纬度为空  按照排序走
            appletsPublicJishibanList.forEach(kv->{
                AppletsJiShiBanData appletsJiShiBanData = new AppletsJiShiBanData();
                appletsJiShiBanData.setName(kv.getMechanismName());
                appletsJiShiBanData.setPhone(kv.getMechanismPhone());
                appletsJiShiBanData.setAddress(kv.getMechanismAddress());
                appletsJiShiBanData.setOriginalId(kv.getOriginalId());
                appletsJiShiBanData.setAppId(kv.getAppid());
                double distance = DistanceCalculation.isTrue(longitude,latitude,kv.getLongitude(),kv.getLatitude());
                appletsJiShiBanData.setDistance(distance);
                jiShiBanDataList.add(appletsJiShiBanData);
            });
            if (jiShiBanDataList.size()>0){
                jiShiBanDataList.sort(Comparator.comparing(AppletsJiShiBanData::getDistance));
            }
        }else{
            appletsPublicJishibanList.forEach(kv->{
                AppletsJiShiBanData appletsJiShiBanData = new AppletsJiShiBanData();
                appletsJiShiBanData.setName(kv.getMechanismName());
                appletsJiShiBanData.setPhone(kv.getMechanismPhone());
                appletsJiShiBanData.setAddress(kv.getMechanismAddress());
                appletsJiShiBanData.setOriginalId(kv.getOriginalId());
                appletsJiShiBanData.setAppId(kv.getAppid());
                jiShiBanDataList.add(appletsJiShiBanData);
            });
        }
        appletsJshibanPublicView.setDataList(jiShiBanDataList);
        List<CurrencyView> cityList = new ArrayList<>();
        SysPostalcode postalcode = new SysPostalcode();
        postalcode.setCodeType("3");
        postalcode.setProvinceCode("13");
        postalcode.setCityCode("1311");
        List<SysPostalcode>  plist = sysPostalcodeService.selectSysPostalcodeList(postalcode);
        plist.forEach(kv->{
            CurrencyView currencyView = new CurrencyView();
            currencyView.setKey(kv.getCode());
            currencyView.setValue(kv.getCodeName());
            cityList.add(currencyView);
        });
        cityList.sort(Comparator.comparing(CurrencyView::getKey));
        appletsJshibanPublicView.setCityList(cityList);
        return AjaxResult.success(appletsJshibanPublicView);
    }
}
